package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Line;
import com.itheima.pojo.SetmealCount;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;

    @RequestMapping("/getMemberReport1")
    public Result getMemberReport1() {
        Line line=new Line();
        Line line1=new Line();
        Line line2=new Line();
        List<Line> list=new ArrayList<>();
        line.setMonths("2020.1");
        line1.setMonths("2020.2");
        line2.setMonths("2020.3");
        line.setMemberCount(100);
        line1.setMemberCount(200);
        line2.setMemberCount(300);
        list.add(line);
        list.add(line1);
        list.add(line2);
        return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, list);
//        List<String> months=new ArrayList<>();
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.MONTH,-12);
//        for (int i = 0; i < 12; i++) {
//            calendar.add(Calendar.MONTH,1);
//            Date date = calendar.getTime();
//            months.add(new SimpleDateFormat("yyyy.MM").format(date));
//        }
//        List<Integer>memberCount=memberService.findLine(months);
//        Map<String,Integer>map=new HashMap<>();
//
//       return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //会员数量折线图
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        //获得日历对象,获得的就是当前的时间,也正是因为有这个日历对象,
        //所以我们根本不需要查询数据库,直接就可以通过日历对象计算出来的
        Calendar calendar = Calendar.getInstance();
        //计算过去一年的12个月
        //获得当前时间往前推12个月时间
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
        //获得当前的时间往后再推一个月.记住这个当前时间是我们上面已经往前推1年的时间日期了
        //所以这样每次推一个月这样就可以拿到一年的时间了
            calendar.add(Calendar.MONTH, 1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        map.put("months", months);
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    //套餐预约占比饼形图,用的是老师的方法
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //这个就是传到前台的数据
        Map<String, Object> data = new HashMap<>();
        try {
            List<Map<String, Object>> SetmealCount = setmealService.findSetmealCount();
            data.put("SetmealCount", SetmealCount);
            List<String> setmealNames = new ArrayList<>();
            //因为setmealCount里面是包含有name这一项的,所以我们setmealNames就不需要再查了
            for (Map<String, Object> stringObjectMap : SetmealCount) {
                String name = (String) stringObjectMap.get("name");
                setmealNames.add(name);
            }
            data.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //套餐预约占比饼形图,用的是自己的方法,即创建了一个实体类
    @RequestMapping("/getSetmealReport1")
    public Result getSetmealReport1() {
        List<SetmealCount>setmealCount=setmealService.findWe();
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, setmealCount);
    }

    @Reference
    private ReportService reportService;

    //这个是运营数据统计的
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            //这个是因为上面我们已经查询到了,所以这里直接用上面的方法即可,这样就可以取得我们所有的数据
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果,准备将查询到的数据写到excle报表文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //基于我们已有的excle文件,在内存中我们创建一个excle表格对象
            //File.separator这个表示我们有可能不是在windows环境下,所以我们为了都能识别"/",所以我们用File.separator
            String realPath = request.getSession().getServletContext().getRealPath("template" + File.separator + "report_template.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(realPath)));
            //读取第一个工作表
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            //热门套餐循环
            int roeNum=12;
            for (Map map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(roeNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载,所以这里就不能自己new,而是要用response
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
            return null;
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据到PDF文件并提供客户端下载
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){
        try{
            Map<String,Object> result = reportService.getBusinessReportData();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            //动态获取pdf模板文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(jasperPath,result,
                            new JRBeanCollectionDataSource(hotSetmeal));

            //创建输出流，用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            out.flush();
            out.close();

            return null;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
